const { Wallets, Gateway, X509WalletMixin } = require('fabric-network');
const FabricCAServices = require('fabric-ca-client');
const path = require('path');
const fs = require('fs');

async function enrollUser() {
  try {
    // 创建一个钱包
    const walletPath = path.join(process.cwd(), 'wallet');
    const wallet = await Wallets.newFileSystemWallet(walletPath);

    // 创建一个CA客户端对象
    const caInfo = fs.readFileSync('ca-org1.yaml', 'utf8'); // 替换为你的Fabric CA配置文件路径
    const caInfoObject = JSON.parse(caInfo);
    const caTLSCACerts = caInfoObject.tlsCACerts.pem;
    const caClient = new FabricCAServices(caInfoObject.url, { trustedRoots: caTLSCACerts, verify: false }, caInfoObject.caName);

    // 检查钱包中是否已经存在用户身份
    const userIdentity = 'user1';
    const userExists = await wallet.get(userIdentity);
    if (userExists) {
      console.log(`用户 "${userIdentity}" 已经存在于钱包中`);
      return;
    }

    // 注册和获取用户的身份
    const enrollment = await caClient.enroll({
      enrollmentID: 'user1', // 替换为你的用户ID
      enrollmentSecret: 'user1pw' // 替换为你的用户密码
    });

    // 创建X.509证书对象
    const identity = X509WalletMixin.createIdentity('Org1MSP', enrollment.certificate, enrollment.key.toBytes());

    // 将用户身份存储到钱包中
    await wallet.put(userIdentity, identity);
    console.log(`成功注册并将用户身份存储到钱包中：${userIdentity}`);

    // 连接到Fabric网络
    const gateway = new Gateway();
    const connectionOptions = {
      identity: userIdentity,
      wallet,
      discovery: { enabled: true, asLocalhost: true }
    };

    await gateway.connect(connectionOptions);
    console.log('成功连接到Fabric网络');
    
    // ... 进行后续的智能合约部署和调用等操作
    
    // 断开与网关的连接
    gateway.disconnect();
  } catch (error) {
    console.error(`注册用户时出现错误: ${error}`);
    process.exit(1);
  }
}

enrollUser();
